/**
 * 固定资产管理系统 - 自定义Admin JavaScript
 */

// 等待页面加载完成
document.addEventListener('DOMContentLoaded', function() {
    
    // 初始化功能
    initializeCustomFeatures();
    // 首次进入时根据上下文强制抑制全局 CSS 动画/过渡，减少闪烁
    try { toggleSuppression(isSuppressedContext()); } catch(e) {}
    
    // 添加动画效果（在日志页/模态上下文中跳过以避免闪烁）
    if (!isSuppressedContext()) {
        addAnimations();
    }
    
    // 增强表格功能
    enhanceTables();
    
    // 添加快捷键支持
    addKeyboardShortcuts();
    
    // 添加工具提示（在日志页/模态上下文中跳过以避免闪烁）
    if (!isSuppressedContext()) {
        addTooltips();
    }
    
    // 自动刷新功能
    autoRefresh();

    // 监听 Bootstrap 模态的显示/隐藏，动态切换抑制状态
    // 在 show 阶段开启抑制，确保开启动画期间无闪烁；
    // 在 hide 阶段稍后释放抑制，等待 Bootstrap 移除 backdrop 与 class，避免残留抖动。
    document.addEventListener('show.bs.modal', function(ev){
        try {
            // 若已有其它模态处于显示状态，优先关闭以避免多层叠加引起的遮罩/焦点抖动
            const shown = document.querySelectorAll('.modal.show');
            shown.forEach(m => {
                if (ev && ev.target && m === ev.target) return;
                try { if (window.bootstrap && bootstrap.Modal) {
                    const inst = bootstrap.Modal.getInstance(m) || new bootstrap.Modal(m);
                    inst.hide();
                }} catch(_) {}
            });
            toggleSuppression(true);
        } catch(e) {}
    }, { passive: true });
    document.addEventListener('hide.bs.modal', function(){
        try {
            setTimeout(() => {
                try { toggleSuppression(isSuppressedContext()); } catch(e) {}
            }, 120);
        } catch(e) {}
    }, { passive: true });

    // 在完全隐藏后做一次清理，移除遗留的backdrop与 body 上的 modal-open（若已无可见模态）
    document.addEventListener('hidden.bs.modal', function(){
        try {
            setTimeout(() => {
                try {
                    if (!document.querySelector('.modal.show')) {
                        document.body.classList.remove('modal-open');
                        const backdrops = document.querySelectorAll('.modal-backdrop');
                        backdrops.forEach(b => b.remove());
                    }
                    toggleSuppression(isSuppressedContext());
                } catch(_) {}
            }, 50);
        } catch(_) {}
    }, { passive: true });

    // 操作日志：单实例详情模态框动态填充
    const logDetailModalEl = document.getElementById('logDetailModal');
    if (logDetailModalEl) {
        logDetailModalEl.addEventListener('show.bs.modal', function (ev) {
            try {
                const trigger = ev.relatedTarget;
                const logId = trigger && trigger.getAttribute('data-log-id');
                const title = trigger && (trigger.getAttribute('data-title') || '操作详情');
                const titleEl = logDetailModalEl.querySelector('#logDetailModalLabel');
                const bodyEl = logDetailModalEl.querySelector('.modal-body');
                if (titleEl) titleEl.innerHTML = `<i class="fas fa-info-circle me-2"></i>${title}`;
                if (bodyEl) {
                    const src = logId && document.getElementById(`log-detail-content-${logId}`);
                    bodyEl.innerHTML = src ? src.innerHTML : '<div class="text-muted">未找到详情内容</div>';
                }
            } catch(_) {}
        });
        logDetailModalEl.addEventListener('hidden.bs.modal', function () {
            try {
                const bodyEl = logDetailModalEl.querySelector('.modal-body');
                if (bodyEl) bodyEl.innerHTML = '';
            } catch(_) {}
        });
    }

    // 防御性兜底：当点击模态框内的关闭/取消按钮后，如若由于其它事件干扰导致未能正常关闭，则强制通过 Bootstrap API 关闭
    document.addEventListener('click', function(e){
        const trigger = e.target.closest('.btn-close, [data-bs-dismiss="modal"], [data-dismiss="modal"]');
        if (!trigger) return;
        const modalEl = trigger.closest('.modal');
        if (!modalEl) return;
        // 让 Bootstrap 先处理点击；若短暂延时后仍处于显示态则主动关闭
        setTimeout(() => {
            try {
                if (modalEl.classList.contains('show') && window.bootstrap && bootstrap.Modal) {
                    const inst = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
                    inst.hide();
                }
            } catch(_) { /* noop */ }
        }, 50);
    }, { passive: true });
});

/**
 * 初始化自定义功能
 */
function initializeCustomFeatures() {
    // 添加页面加载进度条
    addProgressBar();
    
    // 添加返回顶部按钮
    addBackToTopButton();
    
    // 添加侧边栏切换功能
    addSidebarToggle();
    
    // 初始化搜索功能
    initializeSearch();
}

// 判断是否处于需要抑制特效的上下文（资产日志页/模态框）
function isSuppressedContext() {
    try {
        return (
            document.body.classList.contains('modal-open') ||
            !!document.querySelector('.modal.show') ||
            !!document.querySelector('#assetLogsContainer') ||
            !!document.querySelector('.asset-logs') ||
            !!document.querySelector('.related-logs')
        );
    } catch (e) { return false; }
}

// 全局抑制样式注入与切换（在日志页/模态中禁用 CSS 过渡/动画与悬停位移）
function ensureSuppressionStyleTag() {
    if (document.getElementById('ui-suppress-style')) return;
    const style = document.createElement('style');
    style.id = 'ui-suppress-style';
    style.type = 'text/css';
    style.textContent = `
      /* 开启抑制时，全面禁用动画与过渡，移除常见悬停位移与阴影，以防止重绘抖动 */
      .suppress-animations *, html.suppress-animations * {
        transition: none !important;
        animation: none !important;
        scroll-behavior: auto !important;
        will-change: auto !important;
      }
      .suppress-animations .card:hover,
      html.suppress-animations .card:hover,
      .suppress-animations .dropdown-item:hover,
      html.suppress-animations .dropdown-item:hover,
      .suppress-animations #back-to-top,
      html.suppress-animations #back-to-top {
        transform: none !important;
        box-shadow: none !important;
      }
      /* 避免按钮点击波纹类动画 */
      .suppress-animations .btn::after,
      html.suppress-animations .btn::after { animation: none !important; transition: none !important; }
      /* 任何模态显示期间，强制关闭过渡与动画，避免内容与遮罩闪烁 */
      .modal.show,
      .modal.show *,
      .modal-backdrop,
      .modal.fade,
      .modal-backdrop.fade {
        transition: none !important;
        animation: none !important;
      }
    `;
    document.head.appendChild(style);
}

function toggleSuppression(enable) {
    ensureSuppressionStyleTag();
    const root = document.documentElement; // 使用 html 标签以提升优先级
    if (enable) {
        root.classList.add('suppress-animations');
    } else {
        root.classList.remove('suppress-animations');
    }
}

/**
 * 添加页面加载进度条
 */
function addProgressBar() {
    const progressBar = document.createElement('div');
    progressBar.id = 'loading-progress';
    progressBar.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 0%;
        height: 3px;
        background: linear-gradient(90deg, #3498db, #2980b9);
        z-index: 9999;
        transition: width 0.3s ease;
        box-shadow: 0 0 10px rgba(52, 152, 219, 0.5);
    `;
    document.body.appendChild(progressBar);
    
    // 模拟加载进度
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 30;
        if (progress >= 100) {
            progress = 100;
            clearInterval(interval);
            setTimeout(() => {
                progressBar.style.opacity = '0';
                setTimeout(() => progressBar.remove(), 300);
            }, 500);
        }
        progressBar.style.width = progress + '%';
    }, 100);
}

/**
 * 添加返回顶部按钮
 */
function addBackToTopButton() {
    const backToTop = document.createElement('div');
    backToTop.innerHTML = '<i class="fas fa-arrow-up"></i>';
    backToTop.id = 'back-to-top';
    backToTop.style.cssText = `
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #3498db, #2980b9);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        opacity: 0;
        transform: translateY(100px);
        transition: all 0.3s ease;
        z-index: 1000;
        box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
    `;
    
    document.body.appendChild(backToTop);
    
    // 显示/隐藏逻辑
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            backToTop.style.opacity = '1';
            backToTop.style.transform = 'translateY(0)';
        } else {
            backToTop.style.opacity = '0';
            backToTop.style.transform = 'translateY(100px)';
        }
    }, { passive: true });
    
    // 点击回到顶部
    backToTop.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    // 悬停效果
    backToTop.addEventListener('mouseenter', () => {
        if (isSuppressedContext()) return;
        backToTop.style.transform = 'translateY(-5px) scale(1.1)';
        backToTop.style.boxShadow = '0 8px 25px rgba(52, 152, 219, 0.4)';
    }, { passive: true });
    
    backToTop.addEventListener('mouseleave', () => {
        backToTop.style.transform = 'translateY(0) scale(1)';
        backToTop.style.boxShadow = '0 5px 15px rgba(52, 152, 219, 0.3)';
    }, { passive: true });
}

/**
 * 添加侧边栏切换功能
 */
function addSidebarToggle() {
    const toggleBtn = document.querySelector('.sidebar-toggle');
    if (toggleBtn) {
        toggleBtn.addEventListener('click', () => {
            const sidebar = document.querySelector('.main-sidebar');
            if (sidebar) {
                sidebar.style.transition = 'all 0.3s ease';
            }
        });
    }
}

/**
 * 初始化搜索功能
 */
function initializeSearch() {
    const searchInputs = document.querySelectorAll('input[type="search"], .searchbox input');
    
    searchInputs.forEach(input => {
        // 添加搜索图标
        const searchIcon = document.createElement('i');
        searchIcon.className = 'fas fa-search';
        searchIcon.style.cssText = `
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #3498db;
            pointer-events: none;
        `;
        
        const container = input.parentNode;
        container.style.position = 'relative';
        container.appendChild(searchIcon);
        
        // 实时搜索
        let searchTimeout;
        input.addEventListener('input', () => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                // 这里可以添加AJAX搜索逻辑
                console.log('搜索:', input.value);
            }, 300);
        }, { passive: true });
    });
}

/**
 * 添加动画效果
 */
function addAnimations() {
    // 在抑制上下文中禁用入场/悬停等动画，减少repaint/合成层抖动
    if (isSuppressedContext()) return;
    // 为卡片添加入场动画
    const cards = document.querySelectorAll('.card, .box, .info-box');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(50px)';
        card.style.transition = 'all 0.6s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });
    
    // 为按钮添加波纹效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            if (isSuppressedContext()) return; // 抑制Ripple
            const ripple = document.createElement('span');
            const rect = button.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                left: ${x}px;
                top: ${y}px;
                width: ${size}px;
                height: ${size}px;
                border-radius: 50%;
                background: rgba(255, 255, 255, 0.6);
                transform: scale(0);
                animation: ripple 0.6s linear;
                pointer-events: none;
            `;
            
            button.style.position = 'relative';
            button.style.overflow = 'hidden';
            button.appendChild(ripple);
            
            setTimeout(() => ripple.remove(), 600);
        });
    });
}

/**
 * 增强表格功能
 */
function enhanceTables() {
    const tables = document.querySelectorAll('table');
    
    tables.forEach(table => {
        // 添加表格排序功能
        addTableSorting(table);
        
        // 添加行悬停效果
        const rows = table.querySelectorAll('tbody tr');
        const isSuppressedContext = () => {
            return (
                document.body.classList.contains('modal-open') ||
                !!table.closest('.modal') ||
                !!document.querySelector('#assetLogsContainer') ||
                !!table.closest('#assetLogsContainer, .asset-logs, .related-logs')
            );
        };
        rows.forEach(row => {
            row.addEventListener('mouseenter', () => {
                if (isSuppressedContext()) return;
                row.style.backgroundColor = 'rgba(52, 152, 219, 0.08)';
                row.style.transform = 'scale(1.005)';
                row.style.willChange = 'transform, background-color';
            }, { passive: true });
            
            row.addEventListener('mouseleave', () => {
                row.style.backgroundColor = '';
                row.style.transform = 'scale(1)';
                row.style.willChange = '';
            }, { passive: true });
        });
        
        // 添加表格筛选功能
        addTableFilter(table);
    });
}
function addTableSorting(table) {
    const headers = table.querySelectorAll('thead th');
    
    headers.forEach((header, index) => {
        if (header.textContent.trim() && !header.querySelector('input')) {
            header.style.cursor = 'pointer';
            header.style.userSelect = 'none';
            header.classList.add('sortable');
            
            header.addEventListener('click', () => {
                const tbody = table.querySelector('tbody');
                const rows = Array.from(tbody.querySelectorAll('tr'));
                
                const isAscending = header.classList.contains('sort-asc');
                
                // 清除其他列的排序标识
                headers.forEach(h => {
                    h.classList.remove('sort-asc', 'sort-desc');
                });
                
                // 设置当前列的排序标识
                header.classList.add(isAscending ? 'sort-desc' : 'sort-asc');
                
                // 排序行
                rows.sort((a, b) => {
                    const aValue = a.cells[index].textContent.trim();
                    const bValue = b.cells[index].textContent.trim();
                    
                    const comparison = aValue.localeCompare(bValue, undefined, {
                        numeric: true,
                        sensitivity: 'base'
                    });
                    
                    return isAscending ? -comparison : comparison;
                });
                
                // 重新插入排序后的行
                rows.forEach(row => tbody.appendChild(row));
            });
        }
    });
}

/**
 * 添加表格筛选功能
 */
function addTableFilter(table) {
    const thead = table.querySelector('thead');
    if (!thead) return;
    
    const filterRow = document.createElement('tr');
    filterRow.className = 'filter-row';
    
    const headers = thead.querySelectorAll('th');
    headers.forEach((header, index) => {
        const filterCell = document.createElement('th');
        filterCell.style.padding = '5px';
        
        if (header.textContent.trim() && !header.querySelector('input')) {
            const filterInput = document.createElement('input');
            filterInput.type = 'text';
            filterInput.placeholder = '筛选...';
            filterInput.style.cssText = `
                width: 100%;
                padding: 5px 10px;
                border: 1px solid #ddd;
                border-radius: 15px;
                font-size: 12px;
            `;
            
            filterInput.addEventListener('input', () => {
                filterTable(table, index, filterInput.value);
            });
            
            filterCell.appendChild(filterInput);
        }
        
        filterRow.appendChild(filterCell);
    });
    
    thead.appendChild(filterRow);
}

/**
 * 表格筛选逻辑
 */
function filterTable(table, columnIndex, filterValue) {
    const tbody = table.querySelector('tbody');
    const rows = tbody.querySelectorAll('tr');
    
    rows.forEach(row => {
        const cell = row.cells[columnIndex];
        if (cell) {
            const cellText = cell.textContent.toLowerCase();
            const filter = filterValue.toLowerCase();
            
            if (cellText.includes(filter)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        }
    });
}

/**
 * 添加快捷键支持
 */
function addKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
        // Ctrl + S 保存
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            const saveBtn = document.querySelector('input[type="submit"], button[type="submit"]');
            if (saveBtn) {
                saveBtn.click();
                showNotification('正在保存...', 'info');
            }
        }
        
        // Ctrl + N 新建
        if (e.ctrlKey && e.key === 'n') {
            e.preventDefault();
            const addBtn = document.querySelector('.btn[href*="add"]');
            if (addBtn) {
                window.location.href = addBtn.href;
            }
        }
        
        // Shift + ESC 强制关闭所有模态框（防止抖动/卡死）
        if (e.key === 'Escape' && e.shiftKey) {
            e.preventDefault();
            try { if (window.forceCloseAllModals) window.forceCloseAllModals(); } catch(_) {}
            return;
        }

        // ESC 关闭当前模态框
        if (e.key === 'Escape') {
            const modal = document.querySelector('.modal.show');
            if (modal) {
                const closeBtn = modal.querySelector('.btn-close, [data-bs-dismiss="modal"], [data-dismiss="modal"]');
                if (closeBtn) {
                    closeBtn.click();
                } else {
                    try {
                        if (window.bootstrap && bootstrap.Modal) {
                            const instance = bootstrap.Modal.getInstance(modal) || new bootstrap.Modal(modal);
                            instance.hide();
                        }
                    } catch (err) { /* noop */ }
                }
            }
        }
    });
}

// 全局：强制关闭所有模态框，并清理 backdrops 与 body 状态；暴露到 window 便于控制台/快捷键调用
if (!window.forceCloseAllModals) {
    window.forceCloseAllModals = function(forceSuppress = true) {
        try {
            if (forceSuppress) toggleSuppression(true);
        } catch(_) {}
        try {
            document.querySelectorAll('.modal.show, .modal.fade').forEach(m => {
                try {
                    if (window.bootstrap && bootstrap.Modal) {
                        const inst = bootstrap.Modal.getInstance(m) || new bootstrap.Modal(m);
                        inst.hide();
                    }
                } catch(_) {}
                // 兜底：直接移除显示类，避免卡死
                m.classList.remove('show');
                m.setAttribute('aria-hidden', 'true');
                m.style.display = 'none';
            });
        } catch(_) {}
        // 清理 backdrop 与 body 状态
        try {
            document.body.classList.remove('modal-open');
            document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
        } catch(_) {}
        // 稍后释放抑制（或根据上下文自动决定）
        setTimeout(() => { try { toggleSuppression(isSuppressedContext()); } catch(_) {} }, 120);
    };
}

/**
 * 添加工具提示
 */
function addTooltips() {
    if (isSuppressedContext()) return; // 在日志/模态上下文中禁用自定义 tooltip
    // 为有title属性的元素添加自定义工具提示
    const elementsWithTitle = document.querySelectorAll('[title]');
    
    elementsWithTitle.forEach(element => {
        const title = element.getAttribute('title');
        element.removeAttribute('title');
        
        element.addEventListener('mouseenter', (e) => {
            if (isSuppressedContext()) return;
            const tooltip = document.createElement('div');
            tooltip.textContent = title;
            tooltip.style.cssText = `
                position: absolute;
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 8px 12px;
                border-radius: 6px;
                font-size: 12px;
                z-index: 10000;
                pointer-events: none;
                white-space: nowrap;
                opacity: 0;
                transition: opacity 0.3s ease;
            `;
            
            document.body.appendChild(tooltip);
            
            const rect = element.getBoundingClientRect();
            tooltip.style.left = (rect.left + rect.width / 2 - tooltip.offsetWidth / 2) + 'px';
            tooltip.style.top = (rect.top - tooltip.offsetHeight - 8) + 'px';
            
            setTimeout(() => tooltip.style.opacity = '1', 10);
            
            element.addEventListener('mouseleave', () => {
                tooltip.style.opacity = '0';
                setTimeout(() => tooltip.remove(), 300);
            }, { once: true });
        }, { passive: true });
    });
}

/**
 * 自动刷新功能
 */
function autoRefresh() {
    // 检查是否在列表页面
    if (window.location.pathname.includes('/admin/') && 
        !window.location.pathname.includes('/add/') && 
        !window.location.pathname.includes('/change/')) {
        
        // 添加自动刷新开关
        const autoRefreshToggle = document.createElement('div');
        autoRefreshToggle.innerHTML = `
            <label style="margin: 10px; color: #666;">
                <input type="checkbox" id="auto-refresh-toggle"> 自动刷新 (30秒)
            </label>
        `;
        
        const toolbar = document.querySelector('.toolbar, .actions') || document.querySelector('.content-header');
        if (toolbar) {
            toolbar.appendChild(autoRefreshToggle);
        }
        
        const toggle = document.getElementById('auto-refresh-toggle');
        let refreshInterval;
        
        toggle.addEventListener('change', () => {
            if (toggle.checked) {
                refreshInterval = setInterval(() => {
                    window.location.reload();
                }, 30000);
                showNotification('自动刷新已启用', 'success');
            } else {
                clearInterval(refreshInterval);
                showNotification('自动刷新已关闭', 'info');
            }
        });
    }
}

/**
 * 显示通知消息
 */
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        opacity: 0;
        transform: translateX(100px);
        transition: all 0.3s ease;
        max-width: 300px;
    `;
    
    // 根据类型设置颜色
    const colors = {
        success: 'linear-gradient(135deg, #27ae60, #2ecc71)',
        error: 'linear-gradient(135deg, #e74c3c, #c0392b)',
        warning: 'linear-gradient(135deg, #f39c12, #e67e22)',
        info: 'linear-gradient(135deg, #3498db, #2980b9)'
    };
    
    notification.style.background = colors[type] || colors.info;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateX(0)';
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100px)';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

/**
 * 添加CSS动画样式
 */
const style = document.createElement('style');
style.textContent = `
    @keyframes ripple {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
    
    .filter-row input:focus {
        outline: none;
        border-color: #3498db;
        box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
    }
`;
document.head.appendChild(style);